package com.fly.handler;

import com.fly.domain.Menu;
import com.fly.service.MenuService;
import com.fly.vo.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.List;

import static org.springframework.web.reactive.function.BodyInserters.fromObject;

/**
 * @author Fly
 * @Description
 * @Date Created in 14:12 2018/1/24
 * @Modified by
 */
@Component
public class MenuHandler {

    private final MenuService menuService;

    @Autowired
    public MenuHandler(MenuService menuService) {
        this.menuService = menuService;
    }

    /**
     * 保存
     * @param serverRequest
     * @return
     */
    public Mono<ServerResponse> save(ServerRequest serverRequest){
        Mono<Menu> menuMono = serverRequest.bodyToMono(Menu.class);
        menuService.save(menuMono.block());
        Response response = new Response(true,"保存成功",null);
        return ServerResponse.ok().body(fromObject(response));
    }

    /**
     * 根据parentID获取树形数据
     * @param serverRequest
     * @return
     */
    public Mono<ServerResponse> getByParentId(ServerRequest serverRequest){
        Long parentId = Long.valueOf(serverRequest.pathVariable("parentId"));
        List<Menu> menuList = menuService.getTreeData(parentId);
        return ServerResponse.ok().body(Flux.fromIterable(menuList),Menu.class);
    }

    /**
     * 根据parentID获取树形数据
     * @param serverRequest
     * @return
     */
    public Mono<ServerResponse> getByRoleId(ServerRequest serverRequest){
        Long roleId = Long.valueOf(serverRequest.pathVariable("roleId"));
        List<Menu> menuList = menuService.getTreeDataByRoleId(roleId);
        return ServerResponse.ok().body(Flux.fromIterable(menuList),Menu.class);
    }
    /**
     * 查询列表
     * @param serverRequest
     * @return
     */
    public Mono<ServerResponse> list(ServerRequest serverRequest){
        Flux<Menu> menuFlux = Flux.fromIterable(menuService.findAll());
        return ServerResponse.ok().body(menuFlux,Menu.class);
    }

    /**
     * 获取当前用户授权菜单
     * @param serverRequest
     * @return
     */
    public Mono<ServerResponse> currentMenu(ServerRequest serverRequest){
        Flux<Menu> menuFlux = Flux.fromIterable(menuService.getCurrentMenus());
        return ServerResponse.ok().body(menuFlux,Menu.class);
    }
}
